import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Menu,
  message,
  Divider, Modal, Dropdown, Icon, DatePicker,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import UpdateForm from './createFrom';
import DescView from './descView';
import InviteList from './inviteList';
import styles from '../UserManage.less';
import { powerBtnFunc } from '@/utils/utils';

const FormItem = Form.Item;

/* eslint react/no-multi-comp:0 */
@connect(({ platuser, loading }) => ({
  platuser,
  loading: loading.models.platuser,
}))

@Form.create()
class DeptManage extends PureComponent {
  state = {
    InviteView: false,
    modalVisible: false,
    lookDescView: false,
    selectedRows: {},
    formValues: {},
    pagination: {
      pageNo: 1,
      pageSize: 15,
    },
  };


  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'platuser/fetch',
      payload: {},
    });

  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    this.setState({
      pagination: {
        pageNo: pagination.current,
        pageSize: 15,
      },
    });
    const params = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
    };

    dispatch({
      type: 'platuser/fetch',
      payload: params,
    });
  };
  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'platuser/fetch',
      payload: {},
    });
  };


  //搜索
  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'platuser/fetch',
        payload: values,
      });
    });
  };
  //新建显示窗口
  handleModalVisible = flag => {
    const { dispatch } = this.props;
    this.setState({
      modalVisible: !!flag,
    }, () => {
      if (!!flag) {
        dispatch({
          type: 'platuser/couponList',
        });
      }
    });
  };

  //查看
  handleLookDesc = (flag, record) => {
    const { dispatch } = this.props;

    this.setState({
      lookDescView: !!flag,
      selectedRows: record,
    }, () => {
      if (!!flag) {
        dispatch({
          type: 'platuser/getDesc',
          payload: { userNo: record.userNo },
        });
      }
    });
  };
  //新建请求
  handleAdd = fields => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;
    let obj = {
      userNo: selectedRows.userNo,
      ...fields,
    };
    dispatch({
      type: 'platuser/send',
      payload: obj,
      callback: (response) => {
        if (response.code === 200) {
          message.success('发放成功');
          dispatch({
            type: 'platuser/fetch',
          });
        } else {
          message.error(response.errMsg);
        }
        this.handleModalVisible(false);
      },
    });

  };


  renderSimpleForm() {
    const { form: { getFieldDecorator } } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="手机号">
              {getFieldDecorator('mobile')(<Input placeholder="请输入手机号"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="用户姓名">
              {getFieldDecorator('appUserName')(<Input placeholder="请输入用户姓名"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="开始时间">
              {getFieldDecorator('startTime')(<DatePicker placeholder="选择时间"
                                                          style={{ width: '100%' }}/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="结束时间">
              {getFieldDecorator('endTime')(<DatePicker placeholder="选择时间"
                                                        style={{ width: '100%' }}/>)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
        <span className={styles.submitButtons}>
        <Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>

        </span>
          </Col>
        </Row>
      </Form>
    );
  }

  selectOption = (key, current) => {
    this.setState({
      selectedRows: current,
    }, () => {
      if (key === 'reward') {
        this.handleModalVisible(true);
      } else if (key === 'user') {
        this.handleInviteView(true);
      }
    });

  };
  handleInviteView = (flag) => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;
    this.setState({
      InviteView: flag,
    }, () => {
      if (flag) {
        dispatch({
          type: 'platuser/userList',
          payload: {
            userNo: selectedRows.userNo,
          },
        });
      }
    });

  };

  render() {
    const { platuser: { data, couponList, detail, userList }, loading } = this.props;
    const { selectedRows, modalVisible, lookDescView, InviteView } = this.state;
    const MoreBtn = props => (
      <Dropdown
        overlay={
          <Menu onClick={({ key }) => this.selectOption(key, props.current)}>
            {
              powerBtnFunc('100176',
                <Menu.Item key="user">邀请人列表</Menu.Item>,
              )}
            {
              powerBtnFunc('100179',
                <Menu.Item key="reward">发放奖励</Menu.Item>,
              )}
          </Menu>
        }>
        <a>
          更多 <Icon type="down"/>
        </a>
      </Dropdown>
    );
    const columns = [
      {
        title: '用户编号',
        dataIndex: 'userNo',
        key: 'userNo',
      },

      {
        title: '手机号',
        dataIndex: 'mobile',
        key: 'mobile',
      },

      {
        title: '用户名称',
        dataIndex: 'userName',
        key: 'userName',
      },
      {
        title: '状态',
        dataIndex: 'account',
        key: 'account',
        render: val =>
          val === 1 ? '已实名' : '未实名',
      },
      {
        title: '邀请人数',
        dataIndex: 'inviteNum',
        key: 'inviteNum',
      },
      {
        title: '邀请码',
        dataIndex: 'inviteCode',
        key: 'inviteCode',
      },
      {
        title: '注册时间',
        dataIndex: 'regTime',
        key: 'regTime',
      },
      {
        title: '操作',
        key: 'dataIndex',
        render: (text, record) => (
          <Fragment>

            {
              powerBtnFunc('100177',
                [<a key={'view'} onClick={() => this.handleLookDesc(true, record)}>查看</a>,
                  <Divider key={'divider'} type="vertical"/>],
              )
            }
            <MoreBtn current={record}/>
          </Fragment>
        ),
      },
    ];

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };

    return (
      <PageHeaderWrapper title="用户管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              rowKey={'deptNo'}
              rowSelectHide={true}
              columns={columns}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <DescView
          handleLookDesc={this.handleLookDesc}
          selectedRows={detail ? detail : {}}
          lookDescView={lookDescView}/>

        <UpdateForm
          {...parentMethods}
          modalVisible={modalVisible}
          values={selectedRows}
          data={data}
          couponList={couponList}
        />
        {userList ?
          <InviteList
            InviteView={InviteView}
            userList={userList}
            selectedRows={selectedRows}
            handleInviteView={this.handleInviteView}
          /> : ''}

      </PageHeaderWrapper>
    );
  }
}

export default DeptManage;
